package biz

import (
	"context"
	"manage/api/class"
	"manage/internal/errors"

	"net/http"

	"github.com/gin-gonic/gin"
)

func (u *APIUseCase) Class() *Method {
	// 获取班级服务
	remoteName := "班级服务"
	remoteClass := u.Repo.Class // 远程调用接口(grpc)

	return &Method{

		Get: func(c *gin.Context) {

			classId := c.Param("class_id")

			getStudents := func() []StudentClass {
				resp, err := u.Repo.GetStudentByClassID(classId)
				if err != nil {
					return nil
				}
				return resp
			}

			remoteClass(func(ctx context.Context, csc class.ClassServiceClient) {
				resp, err := csc.GetClass(ctx, &class.GetClassRequest{
					ClassId: classId,
				})
				if errors.CheckErr(c, err, remoteName, resp.Code, resp.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: resp.Code,
						Msg:  resp.Msg,
						Data: gin.H{
							"class_info":   resp.ClassInfo,
							"student_list": getStudents(),
						},
					})
				}
			})
		},

		Post: func(c *gin.Context) {

			id := c.PostForm("teacher_id")
			cname := c.PostForm("class_name")

			remoteClass(func(ctx context.Context, csc class.ClassServiceClient) {
				resp, err := csc.CreateClass(ctx, &class.CreateClassRequest{
					TeacherId: id,
					ClassName: cname,
				})

				if errors.CheckErr(c, err, remoteName, resp.Code, resp.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: resp.Code,
						Msg:  resp.Msg,
						Data: gin.H{"class_id": resp.ClassId},
					})
				}
			})
		},

		Put: func(c *gin.Context) {

			classId := c.Param("class_id")
			teacherId := c.PostForm("teacher_id")
			cname := c.PostForm("class_name")

			remoteClass(func(ctx context.Context, csc class.ClassServiceClient) {
				resp, err := csc.UpdateClass(ctx, &class.UpdateClassRequest{
					TeacherId: teacherId,
					ClassName: cname,
					ClassId:   classId,
				})
				if errors.CheckErr(c, err, remoteName, resp.Code, resp.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: resp.Code,
						Msg:  resp.Msg,
						Data: "",
					})
				}
			})
		},

		Delete: func(c *gin.Context) {

			classId := c.Param("class_id")

			remoteClass(func(ctx context.Context, csc class.ClassServiceClient) {
				resp, err := csc.DeleteClass(ctx, &class.DeleteClassRequest{
					ClassId: classId,
				})
				if errors.CheckErr(c, err, remoteName, resp.Code, resp.Msg) {

					_ = u.Repo.RemoveStudentsFromClass(classId) // 移除学生

					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: resp.Code,
						Msg:  resp.Msg,
						Data: "",
					})
				}
			})
		},
	}
}
